﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using InfoStrat.VE;
using System.Windows.Media;
using System.Collections.ObjectModel;
using Cinch;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using BingVis.Common;

namespace BingVis.WPFClient
{
    public class PushPinLatLongComparer : IEqualityComparer<VEPushPin>
    {
        #region IEqualityComparer<VEPushPin> Members

        public bool Equals(VEPushPin x, VEPushPin y)
        {
            return (x.Latitude == y.Latitude) && (x.Longitude == y.Longitude);
        }

        public int GetHashCode(VEPushPin obj)
        {
            return obj.GetHashCode();
        }

        #endregion
    }


    class TransitStopToPushPinConverter : IValueConverter
    {
        private static StopNameToColorConverter colorConverter = new StopNameToColorConverter();        

        public TransitStopToPushPinConverter()
        {
            
        }

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var pins = (from s in (value as IEnumerable<TransitStopViewModel>)
                        let stop = s.Stop
                        select new VEPushPin(new VELatLong(stop.Latitude, stop.Longitude))
                             {
                                 Content = stop.Name,
                                 Tag = stop,
                                 PushPinBackground = (SolidColorBrush)colorConverter.Convert(stop.Name, null, null, null)
                             })
                             .Distinct(new PushPinLatLongComparer())
                             .ToList();
                            
            
            
            // Add some click bindings.
            foreach (var pin in pins)
            {   
                // My Attempt at weak referencing...                
                pin.Click += new EventHandler<VEPushPinClickedEventArgs>(OnPinClicked)
                                    .MakeWeak(eh => pin.Click -= eh);
            }

            return pins;
        }

        private void OnPinClicked(object sender, VEPushPinClickedEventArgs args)
        {
            var stop = ((VEPushPin)sender).Tag as ITransitStop;
            if ( stop != null )
                AppMediator.Instance.NotifyColleagues<ITransitStop>(EventNames.SelectedStop, stop);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
